package com.cf.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cf.entity.SysUserEntity;
import com.cf.utils.R;
import com.cf.utils.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 登录相关
 * 
 */
@Controller
public class SysLoginController {
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	private Producer producer;
	private static final Logger log = LoggerFactory
			.getLogger(SysLoginController.class);

	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字验证码
		String text = producer.createText();
		// 生成图片验证码
		BufferedImage image = producer.createImage(text);
		// 保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.flush();
	}

	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(@RequestParam("username") String username,
			@RequestParam("password") String password,
			@RequestParam("captcha") String captcha) throws IOException {

		if (!StrUtil.equals(captcha, "H5-APP")) {

			String kaptcha = ShiroUtils
					.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
			if (!captcha.equalsIgnoreCase(kaptcha)) {
				return R.error("验证码不正确");
			}
		}

		try {
			Subject subject = ShiroUtils.getSubject();
			// MD5加密
			password = new Md5Hash(password).toHex();
			UsernamePasswordToken token = new UsernamePasswordToken(username,
					password);

			subject.login(token);
			response.setHeader("Authorization",
					subject.getSession().getId().toString());
			SysUserEntity user = ShiroUtils.getUserEntity();
			Map<String, Object> map = new HashMap<String, Object>();
			map = BeanUtil.beanToMap(user);
			map.remove("password");
			return R.ok().put("user", map);
		} catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		} catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		} catch (LockedAccountException e) {
			return R.error(e.getMessage());
		} catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}

	}


//	@ResponseBody
//	@RequestMapping(value = "/sys/logout", method = RequestMethod.GET)
//	public R logout() {
//		R r = new R();
//		r.put("statusCode", 405);
//
//		ShiroUtils.logout();
//		return r;
//
//	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/sys/logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:/login.html";
	}
	/**
	 * 网页过期处理 *
	 */
	@RequestMapping(value = "/inValid")
	public @ResponseBody R expired(HttpServletResponse response) {
		response.setHeader("statusCode", "403");
		R r = new R();
		r.put("statusCode", 403);
		r.put("msg", "网页已过期或其他问题无法访问！");
		return r;
	}
}
